package com.atgouwu.mall.auth.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 需单点登录
 */
@RestController
@RequestMapping("auth/sso")
public class SsoController {

    //单点登录:第一次session为空(token可选参数),携带当前地址重定向到sso服务登录页
    //sso登录页:从sso的cookie获取token,有就携带token返回原服务,没有就账号密码登录
    //sso输入账号密码登录:用户信息存入redis,token存入sso的cookie,登录成功携带token重定向到原服务
    //返回此页:判断token不为空,调sso服务根据token从redis获取用户信息存入session, 判断session有值,返回登录成功用户信息
    @GetMapping(value = "/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:9008/sso/login/userinfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser", body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:" + "http://localhost:9008/sso/login/login.html" + "?redirect_url=http://localhost:9007/auth/sso/employees";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "employees";
        }
    }

    //跨浏览器共享数据(cookie,storage都不能跨浏览器)
    //第二个浏览器登录时会挤掉另外一个,限制用户只能登录一个或可登录多个账号

}
